﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AyFrame.DbEntity;
using AyFrame.DbEntity.Models;
using AyFrame.Dto;
using AyFrame.IServices;
using AyFrame.NSerialLog;

namespace AyFrame.Services
{
    public class AreaService : BaseService<Area>, IAreaService
    {
        readonly IMapper _mapper;
        public AreaService(IMapper mapper)
        {
            _mapper = mapper;
        }

        public List<AreaView> GetAll()
        {
            var data = unitOfWork.Queryable<Area>().ToTree(t => t.Children, t => t.ParentId, "root");

            return _mapper.Map<List<AreaView>>(data);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<string> Add(string userId, AreaCreateDto dto)
        {
            var e = await GetSingleAsync(t => t.Name == dto.Name);
            if (e != null) throw new Exception($"已存在【{dto.Name}】");

            var curUser = await GetUser(userId);

            var entity = new Area
            {
                Id = Guid.NewGuid().ToString(),
                Name = dto.Name,
                Ename = dto.Ename,
                ParentId = dto.ParentId,
                AddUid = curUser.Uid,
                UpdateUid = curUser.Uid
            };

            var r = AsInsertable(entity)
                .EnableDiffLogEvent(new { uid = "admin" })
                .ExecuteCommand();

            if (r == 1)
                return entity.Id;
            return null;
        }

        public async Task<AreaView> Update(string userId, AreaUpdateDto dto)
        {
            var curUser = await GetUser(userId);

            var area = GetSingle(t => t.Id == dto.Id);
            if (area == null)
                throw new Exception("数据不存在");

            area = _mapper.Map<Area>(dto);

            area.UpdateUid = curUser.Uid;

            AsUpdateable(area)
                .EnableDiffLogEvent(new { uid = "admin" })
                .ExecuteCommand();

            return _mapper.Map<AreaView>(area);
        }
    }
}
